package com.casicloud.manage.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.casicloud.manage.mapper.UserMapper;
import com.casicloud.manage.mapper.UserRoleMapper;
import com.casicloud.manage.model.User;
import com.casicloud.manage.model.UserRole;
import com.casicloud.manage.service.UserService;
import com.common.sub.util.ArrayUtils;
import com.common.sub.util.PageUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public User findByUserNameAndPassword(User user) {

		return userMapper.findByUserNameAndPassword(user);
	}

	@Override
	public List<User> findByList(User user) {
		return userMapper.findByList(user);
	}

	@Override
	public PageInfo<User> findByPage(PageUtil pageUtil , User user) {
		Page<User> p = PageHelper.startPage(pageUtil.getPage(), pageUtil.getRows());
		userMapper.findByList(user);
		return new PageInfo<User>(p);
	}

	@Override
	public User findByOne(User user) {
		return userMapper.findByOne(user);
	}

	@Override
	public void save(User user) {
		
		userMapper.save(user);
		
	}

	@Override
	public int update(User user) {
		return userMapper.update(user);
	}

	@Override
	public int delete(User user) {
		return userMapper.delete(user);
	}

	@Override
	public int updateRole(User user, Integer... roleIds) {
		UserRole ur = new UserRole();
		ur.setUserId(user.getId());
		
		 
		List<UserRole> urlist = userRoleMapper.findByList(ur);
		List<Integer> newlist = new ArrayList<Integer>();
		List<Integer> oldlist = new ArrayList<Integer>();
		
		for(int i = 0;i<roleIds.length;i++){
			newlist.add(roleIds[i]);
		}
		for(int j = 0;j<urlist.size();j++){
			oldlist.add(urlist.get(j).getRoleId());
		}
		
		
		List<Integer> dellist = ArrayUtils.remove(oldlist, newlist);
		for(Integer rid:dellist){
			UserRole u = new UserRole();
			u.setRoleId(rid);
			u.setUserId(user.getId());
			userRoleMapper.delete(u);
		}
		List<Integer> addlist = ArrayUtils.remove(newlist, oldlist);
		for(Integer rid:addlist){
			UserRole u = new UserRole();
			u.setRoleId(rid);
			u.setUserId(user.getId());
			userRoleMapper.save(u);
		}
		
		
		return addlist.size()+dellist.size();
	}

}
